#include <vector>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>

using namespace std;

class Solution {
public:

    // 704. 二分查找
    // https://leetcode.cn/problems/binary-search/
    int search(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1;

        while (left <= right)
        {
            int mid = (left + right) / 2;
            if (nums[mid] < target)
            {
                left = mid + 1;
            }
            else if (nums[mid] > target)
            {
                right = mid - 1;
            }
            else 
            {
                return mid;
            }
        }
        return -1;
    }

    // 34. 在排序数组中查找元素的第一个和最后一个位置
    // https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
    vector<int> searchRange(vector<int>& nums, int target) {
        int left = 0, right = nums.size() - 1;
        vector<int> ans(2);
        while (left < right)
        {
            int mid = left + (right - left) / 2;
            if (nums[mid] < target)
                left = mid + 1;
            else
                right = mid;
        }
        if (left == right && nums[left] == target)
            ans[0] = left;
        else 
            ans[0] = -1;
        
        left = 0, right = nums.size() - 1;
        while (left < right)
        {
            int mid = left + (right - left + 1) / 2;
            if (nums[mid] > target)
                right = mid - 1;
            else 
                left = mid;
        }
        if (left == right && nums[left] == target)
            ans[1] = left;
        else 
            ans[1] = -1;
        
        return ans;
    }
};